package com.example.servlet;

import jakarta.servlet.ServletContextEvent;
import jakarta.servlet.ServletContextListener;
import jakarta.servlet.annotation.WebListener;
import jakarta.servlet.http.HttpSessionAttributeListener;
import jakarta.servlet.http.HttpSessionBindingEvent;
import jakarta.servlet.http.HttpSessionEvent;
import jakarta.servlet.http.HttpSessionListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@WebListener
public class Listener implements ServletContextListener, HttpSessionListener, HttpSessionAttributeListener {


    final static Logger logger = LoggerFactory.getLogger(Listener.class);

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        /* This method is called when the servlet context is initialized(when the Web application is deployed). */

        System.out.println("应该是服务器初始化,contextInitialized");
        logger.error("应该是服务器初始化,contextInitialized{}", sce);

        sce.getServletContext().setSessionTimeout(1);
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        /* This method is called when the servlet Context is undeployed or Application Server shuts down. */
        System.out.println("应该是服务器关闭,contextDestroyed");
    }

    int i;

    @Override
    public void sessionCreated(HttpSessionEvent se) {
        /* Session is created. */
        System.out.println("应该是创建了个session,sessionCreated" + se.getSession().getId());
        logger.debug("应该是创建了个session,sessionCreated{}", se);

        i++;

        if (i % 3 == 0) {
            se.getSession().invalidate();
        }
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        /* Session is destroyed. */
        System.out.println("应该是销毁了个session,sessionDestroyed" + se.getSession().getId());
    }

    @Override
    public void attributeAdded(HttpSessionBindingEvent sbe) {
        /* This method is called when an attribute is added to a session. */
        System.out.println("应该是创建了个属性," + sbe.getName() + sbe.getValue());
    }

    @Override
    public void attributeRemoved(HttpSessionBindingEvent sbe) {
        /* This method is called when an attribute is removed from a session. */
        System.out.println("应该是删除了个属性," + sbe.getName() + sbe.getValue());
    }

    @Override
    public void attributeReplaced(HttpSessionBindingEvent sbe) {
        /* This method is called when an attribute is replaced in a session. */
        System.out.println("应该是修改了个属性," + sbe.getName() + sbe.getValue());
    }
}
